#include "../Base/Log.h"
#include "../Render/RenderEngine.h"

#include "TextObject.h"

namespace cy_univerX
{
namespace world2d
{

	CTextNode::CTextNode(const render::CTextFont&font, const std::string&text, CSpaceNode* parent)
		:CSpaceNode(parent),m_Text(text),m_Color(0,0,0,1),m_Texture(0)
	{
		m_Font = font;
		m_Dirty = true;
	}

	CTextNode::~CTextNode()
	{
		if (m_Texture)
			delete m_Texture;
	}

	void CTextNode::UpdateTextTexture()const
	{
		render::CAlphaImageData data;
		render::CTextMgr::Instance().CreateTextImage(m_Font, m_Text, data, false);
		if (m_Texture)
		{
			delete m_Texture;
			m_Texture = 0;
		}
		D3D11_TEXTURE2D_DESC desc;
		desc.Width = data.m_Width;
		desc.Height = data.m_Height;
		desc.MipLevels = 1;
		desc.ArraySize = 1;
		desc.Format = DXGI_FORMAT_A8_UNORM;
		desc.SampleDesc.Count = 1;
		desc.SampleDesc.Quality = 0;
		desc.Usage = D3D11_USAGE_IMMUTABLE;
		desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
		desc.CPUAccessFlags = 0;
		desc.MiscFlags = 0;

		D3D11_SUBRESOURCE_DATA ss_data;
		ss_data.pSysMem = data.m_Buff;
		ss_data.SysMemPitch = data.m_Width;

		m_Texture = new render::CTexture2D(desc, ss_data);
		render::CTextMgr::Instance().ReleaseTextImage(data);
		
		m_LocalSize.Set((float)data.m_Width, (float)data.m_Height);
		m_Dirty = false;
	}

	void CTextNode::Render(const float& window_w, const float& window_h, render::CSimpleEffectBase* eff)const
	{
		if (m_Text.size() == 0)
			return;

		if (m_Dirty)
			UpdateTextTexture();
		
		math::CVector3f uv[4];
		uv[0].Set(0,0,0);
		uv[1].Set(1,0,0);
		uv[2].Set(0,1,0);
		uv[3].Set(1,1,0);
		DoRenderQuad(window_w, window_h, eff, m_Color, 
			m_Texture, m_LocalSize, uv);

		ChildRender(window_w, window_h, eff);
	}

}
}